﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Accountability4net.Contact;
using System.Xml;
using System.IO;

namespace Accountability4net.FileMonengineProvider
{
    public class FileContact: BaseContact
    {
        FileMonengineProvider provider_;
        public FileContact(FileMonengineProvider provider)
        {
            provider_ = provider;
        }

        public override IName Name
        {
            get
            {
                if (name_ == null)
                {
                    name_ = new FileName(provider_, this);
                }
                return name_;
            }
            set
            {
                base.Name = value;
            }
        }

        public XmlNode Write(XmlNode element)
        {
            XmlNode node = element.OwnerDocument.CreateElement("contact", element.NamespaceURI);
            element.AppendChild(node);
            XmlUtility.CreateAttribute(node, "id", ID);
            XmlUtility.CreateTextElement(node, "email", Email);
            ((FileName)Name).Write(node);
            if (Photo != null)
            {
                XmlUtility.CreateImageElement(node, "photo", Photo);
            }
            return node;
        }

        public static IContact Parse(XmlNode node)
        {
            return Parse(node, null);
        }

        public static IContact Parse(XmlNode node, FileMonengineProvider provider)
        {
            FileContact contact = new FileContact(provider);
            contact.ID = new Guid(node.Attributes["id"].Value);
            contact.Email = provider.Storage.SelectSingleNode(node, "x:email").InnerText;
            var nameNode = provider.Storage.SelectSingleNode(node, "x:name");
            contact.Name = FileName.Parse(nameNode, provider, contact);
            XmlElement photoElement = (XmlElement)provider.Storage.SelectSingleNode(node, "x:photo");
            if (photoElement != null)
            {
                contact.Photo = XmlUtility.ReadImageElement(photoElement);
            }
            return contact;
        }

    }
}
